import './lib/wxPromise.min.js'
import regeneratorRuntime from './lib/wxPromise.min.js'
import uuidv1 from './lib/uuid/uuid.modified'
import * as API_Address from './api/address'
import * as API_Member from './api/members'
import * as API_Leader from './api/leader'
import * as API_Distribution from './api/distribution'
import * as API_Trade from './api/trade'
import * as API_Passport from './api/passport'
import * as API_Wechat from './api/wechat'
let log = require('./log.js'); // 引用上面的log.js文件
// let livePlayer = requirePlugin('live-player-plugin');
const DEFAULT = {
  // 省
  'province': '浙江省',
  // 市,直辖市返回空
  'city': '舟山市',
  // 区
  'district': '定海区',
  // 地址信息
  'address': '解放西路',
  // 点名称
  'addressName': '定海区解放西路',
  // 详细位置
  'detailAddress': '浙江省舟山市定海区解放西路',
  // 当前建筑物的经纬度
  'buildingPosition': '122.09507,30.014187',
  // 当前位置经纬度
  'longitude': 122.09507,
  'latitude': 30.014187
};

// 小程序自动登录
App({
  // 全局变量
  globalData: {
    data: {},
    // uuid
    uuid: '',
    // 是否已授权
    hasAuth: false,
    // openid
    openid: '',
    unionid: '',
    phone: '',
    // 手机信息
    systemInfo: {},
    // navbar
    navbar: { // 头部信息
      statusBarHeight: 0, // 状态栏高度
      height: 0, // 总高度
      top: 0, // 距离状态栏高
      bottom: 0, // 距离导航栏底部的长度
      right: 0 // 内容右边内边距
    },
    navbarBtn: {
      height: 0,
      width: 0,
      top: 0,
      bottom: 0,
      right: 0
    },
    // 系统默认地址
    defaultLocation: DEFAULT,
    // 位置信息
    locationData: {
      hasAuth: false,
      latitude: DEFAULT.latitude,
      longitude: DEFAULT.longitude,
      province: DEFAULT.province,
      city: DEFAULT.city,
      district: DEFAULT.district,
      addressName: DEFAULT.addressName,
      detailAddress: DEFAULT.detailAddress,
      buildingPosition: DEFAULT.buildingPosition
    },
    // 进入小程序携带参数
    firstOption: {},
    // 默认分享标题
    shareTitle: '水果生鲜百货，优惠多多，在家门口，淘尽全球',
    // 站点名称
    projectName: '门口淘',
    // 苹果手机
    isIphone: -1,
    //苹果手机底部适配
    isIphoneMax: -1,
    // 购物车信息
    cartList: []
  },
  async onLaunch(options) {
    // 获取小程序更新机制兼容
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      // 检查小程序是否有新版本更新
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            })
          })
        }
      })
    } else {
      // 如果getUpdateManager此方法 可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    };
    // 生成uuid
    if (!wx.getStorageSync('uuid')) {
      let _uuid = await uuidv1.v1();
      wx.setStorageSync('uuid', _uuid);
      this.globalData.uuid = _uuid;
    } else {
      this.globalData.uuid = wx.getStorageSync('uuid');
    };
    // 储存参数
    this.globalData.firstOption = options || {};
    // 获取顶部信息
    this.getHeader();
    // 访问链接需要绑定关系
    // 授权检测
    if (!wx.getStorageSync('refresh_token')) {
      // 检查微信是否授权用户信息查询 scope.userInfo
      wx.getSetting({
        success: (res) => {
          let _auth = res.authSetting;
          if (!_auth['scope.userInfo']) {
            this.globalData.hasAuth = false;
            wx.setStorageSync('wxauth', false);
          } else {
            this.globalData.hasAuth = true;
            wx.setStorageSync('wxauth', true);
            // 小程序自动登录
            this.autoLogin();
          }
        }
      })
    };
    this.needShareKey();
    // 获取位置信息
    this.getAmap();
  },
  onShow (options) {
    // 储存参数
    this.globalData.firstOption = options || {};
    // 访问链接需要绑定关系
    this.needShareKey();
  },
  // 获取顶部信息
  getHeader() {
    const systemInfo = wx.getSystemInfoSync();
    const headerBtnPosi = wx.getMenuButtonBoundingClientRect();
    const _statusBarHeight = systemInfo.statusBarHeight;
    let _top = headerBtnPosi.top - _statusBarHeight; // 实际距离顶部距离[胶囊距离顶部距离 - 状态栏高度]
    let _height = _top * 2 + _statusBarHeight + headerBtnPosi.height; // 实际导航栏高度[胶囊实际上下距离 + 状态栏高度 + 胶囊高度]
    let _right = systemInfo.windowWidth - headerBtnPosi.right; // 胶囊实际距离右侧距离[屏幕宽度 - 胶囊right]
    this.globalData.systemInfo = systemInfo;
    this.globalData.navbarBtn = headerBtnPosi;
    this.globalData.isIphone = systemInfo.model.indexOf('iPhone');
    this.globalData.isIphoneMax = systemInfo.model.indexOf('iPhone X', 'iPhone XS', 'iPhone XR', 'iPhone XS Max', 'iPhone 11', 'iPhone 11 pro');
    if (this.globalData.isIphone > -1) {
      _height = _height + 4;
    };
    this.globalData.navbar = {
      statusBarHeight: _statusBarHeight,
      height: _height,
      top: _top,
      bottom: _top,
      right: _right
    };
  },
  // 获取位置信息
  getAmap() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        // 储存获取位置权限信息
        wx.setStorageSync('getLocation', true);
        API_Address.getNearby(res.longitude, res.latitude).then(resposnse => {
          const { address, address_component, formatted_addresses, location } = resposnse;
          const { province, city, district } = address_component;
          const name = formatted_addresses.recommend;
          const { lat, lng } = location;
          let _locationData = { 
            'hasAuth': true,
            'latitude': lat,
            'longitude': lng,
            'address': address,
            'addressName': name,
            'buildingPosition': `${lng},${lat}`,
            'province': province,
            'city': !city ? province : city,
            'district': district,
            'detailAddress': address
          };
          that.globalData.locationData = _locationData;
          const _pageBack = getCurrentPages()[getCurrentPages().length - 1];
          if (_pageBack && _pageBack.route === 'pages/index-group/index/index') {
            _pageBack.onLoad();
            _pageBack.onShow();
          };
        });
      },fail: function (error) {
        // 储存获取位置权限信息
        wx.setStorageSync('getLocation', false);
        log.error(error);
      }
    });
  },
  // 设置计算属性
  setComputed(page) {
    let data = page.data
    let dataKeys = Object.keys(data)
    dataKeys.forEach(dataKey => {
      this.observeComputed(page, page.data, dataKey, page.data[dataKey])
    })
  },
  observeComputed(data, key, val, fn) {
    var dataVal = data[key];
    if (dataVal != null && typeof dataVal === 'object') {
      Object.keys(dataVal).forEach(childKey => { // 遍历val对象下的每一个key
        this.observeComputed(page, dataVal, childKey, dataVal[childKey])
      })
    };
    var that = this;
    Object.defineProperty(data, key, {
      configurable: true,
      enumerable: true,
      get: function () {
        return val
      },
      set: function (newVal) {
        val = newVal
        let computed = page.computed //computed对象，每个值都是函数 
        let keys = Object.keys(computed)
        let firstComputedObj = keys.reduce((prev, next) => {
          page.data.$target = function () {
            page.setData({ [next]: computed[next].call(page) })
          }
          prev[next] = computed[next].call(page)
          page.data.$target = null
          return prev
        }, {})
        page.setData(firstComputedObj)
      }
    })
  },
  // 登录校验
  isLogin() {
    // 如果没有登录
    if (!wx.getStorageSync('refresh_token')) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，要现在去登录吗？',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/auth/login/login' });
          } else {
            // 如果取消登录，并且当前页面为‘订单分享’页，则跳转到团购首页
            let _historyList = getCurrentPages();
            if (_historyList[_historyList.length -1].route === 'pages/order-share/order-share') {
              wx.switchTab({ url: '/pages/index-group/index/index' });
            };
          };
        }
      });
      return false;
    } else {
      return true;
    };
  },
  // 自动登录
  async autoLogin() {
    // 检测是否登录 如果已经登录 或者登录结果为账户未发现 则不再进行自动登录并解析出个人信息
    if (wx.getStorageSync('refresh_token')) return
    const { code } = await wx.pro.login({ timeout: 30000 });
    const uuid = wx.getStorageSync('uuid');
    try {
      let _parmas = { uuid, code };
      API_Passport.getUserInfo(_parmas).then(response => {
        const _firstOption = this.globalData.firstOption;
        if (_firstOption && _firstOption !== {}) {
          this.needShareKey();
        };
        if (response.auto_login === 'true') {
          this.afterLoginInfo(response);
        } else {
          this.globalData.openid = response.openid;
          wx.setStorageSync('openid', response.openid);
          // 获取用户信息
          wx.getUserInfo({
            lang:'zh_CN',
            success:(res)=>{
              _parmas.encrypted_data = res.encryptedData;
              _parmas.iv = res.iv;
              API_Passport.decryptWechat(_parmas).then(codeRes => {
                this.globalData.unionid = codeRes.unionId;
                wx.setStorageSync('unionid', codeRes.unionId);
                wx.setStorageSync('nickName', codeRes.nickName);
              });
            }
          });
        };
      });
    } catch (e) {
      console.log("错误信息", e);
      log.error(e);
    }
  },
  // 登录完成获取基本信息
  async afterLoginInfo(result) {
    const { access_token, refresh_token, uid, openid, unionid } = result;
    // 如果登录成功 存储token(access_token refresh_token) uid 获取用户数据 获取购物车数据
    if (access_token && refresh_token && uid) {
      this.globalData.hasAuth = true;
      wx.setStorageSync('access_token', access_token);
      wx.setStorageSync('refresh_token', refresh_token);
      wx.setStorageSync('uid', uid);
      if (openid) {
        this.globalData.openid = openid;
        wx.setStorageSync('openid', openid);
      };
      if (unionid) {
        this.globalData.unionid = unionid;
        wx.setStorageSync('unionid', unionid);
      };
      // 获取并保存用户信息
      const user = await API_Member.getUserInfo();
      wx.setStorageSync('user', user);
      // 获取用户信息
      await wx.getUserInfo({
        lang: 'zh_CN',
        success: (res) => {
          let _user = JSON.parse(JSON.stringify(user));
          for (const _key in _user) {
            if (!_user[_key]) { // 当条件值为''时去除条件
              delete _user[_key];
            };
          };
          const userInfo = res.userInfo;
          let params = _user || {};
          if (!_user.face) {
            params.face = userInfo.avatarUrl;
            user.face = userInfo.avatarUrl;
          };
          const _userLocation = wx.getStorageSync('userLocation');
          if (!_user.lat && !_user.lng && _userLocation) {
            params.lat = _userLocation.split(',')[1];
            params.lng = _userLocation.split(',')[0];
            user.lat = params.lat;
            user.lng = params.lng;
          };
          // 提交头像 和 经纬度
          API_Member.saveUserInfo(params).then(async () => {
            wx.setStorageSync('user', user);
            this.getUserAllInfo();
            // 刷新当前页面的数据
            if (getCurrentPages().length != 0) {
              getCurrentPages()[getCurrentPages().length - 1].onLoad();
              getCurrentPages()[getCurrentPages().length - 1].onShow();
            };
          });
        }
      });
      // 获取购物车信息
      // const { cart_list } = await API_Trade.getCarts();
      // wx.setStorageSync('shoplist', cart_list);
    };
  },
  // 获取用户所有信息
  getUserAllInfo() {
    API_Member.getUserAllInfo().then(res => {
      const { member, leader, distributor } = res;
      wx.setStorageSync('user', member || '');
      wx.setStorageSync('leader', leader || '');
      wx.setStorageSync('distributor', distributor || '');
    });
  },
  // 消息订阅提示 'PAY_NOTICE,CANCEL_NOTICE_1'
  async sendNotice(tplTypes) {
    let _params = {
      types: tplTypes
    };
    let _tpls = await API_Wechat.getNoticeTpl(_params);
    await wx.requestSubscribeMessage({
      tmplIds: _tpls,
      complete(response) {
        console.log(response)
      }
    });
  },
  // 获取生成分享绑定页面的key,并且储存到缓存中
  getShareKey (url, keyName) {
    if (!wx.getStorageSync('refresh_token')) {
      return;
    };
    const _params = {
      share_url: url
    };
    API_Distribution.getShareKey(_params).then(res => {
      wx.setStorageSync(keyName, res);
    });
  },
  // 分享链接进入，绑定关系
  visitBind (_key, visitType) {
    const _params = {
      share_key: _key,
      visit_type: visitType || 1, // 访问类型，1默认 2直播
      uuid: this.globalData.uuid
    };
    API_Distribution.visitBind(_params).then(res => {
      console.log(res);
    }).catch(error => {
      console.log(error);
    });
  },
  // 访问链接需要绑定关系
  needShareKey () {
    let options = this.globalData.firstOption;
    let _query = options.query;
    if (_query && _query !== {}) {
      let shareKey = '';
      shareKey = _query.shareKey || '';
      if (_query.scene && _query.scene.indexOf('shareKey')) {
        let _scene = decodeURIComponent(_query.scene).split('&');
        shareKey = _scene[_scene.length-1] || '';
      };
      if (shareKey) {
        wx.setStorageSync('shareKey', shareKey);
        this.visitBind(shareKey);
      };
    };
    if (options.scene == 1007 || options.scene == 1008 || options.scene == 1044) {
      let livePlayer = requirePlugin('live-player-plugin');
      livePlayer.getShareParams().then(res => {
        const { openid, share_openid } = res;
        if (openid && share_openid && openid !== share_openid) {
          wx.setStorageSync('shareKey', share_openid);
          this.visitBind(share_openid, 2);
        };
      }).catch(err => {
        console.log('get share params', err)
      });
    };
  },
  // 获取当前团长
  async getCurrentLeader() {
    const { locationData } = this.globalData;
    let _currentData = {};
    let _params = {
      'lat': locationData.latitude,
      'lng': locationData.longitude
    };
    _currentData = await API_Leader.getLastLeader(_params) || {};
    return _currentData;
  },
  // 获取附近团长
  async getLeaderList () {
    const { locationData } = this.globalData;
    let _leaderList = [];
    let _params = {
      'lat': locationData.latitude,
      'lng': locationData.longitude,
      'page_no': 1,
      'page_size': 999
    };
    _leaderList = await API_Leader.getNearLeader(_params) || [];
    return _leaderList;
  },
  // 获取团购购物车
  async getTuanCart () {
    let cartList = [];
    if (wx.getStorageSync('refresh_token')) {
      const { province, city } = this.globalData.locationData;
      let _position = city || province;
      const { cart_list } = await API_Trade.getCarts('SHETUAN_CART', 'all', 'CART', _position);
      cartList = cart_list && cart_list.length ? cart_list[0].sku_list : [];
    };
    this.globalData.cartList = cartList;
    return cartList;
  },
  // 对比购物车更新商品的数量
  cartContrast(dataSource) {
    const { cartList } = this.globalData;
    // dataSource: 数据源[首页商品列表；分组商品列表]
    let useNewData = dataSource.map(item => {
      let itemCart = cartList.filter(cartItem => cartItem.goods_id === item.goods_id && cartItem.sku_id === item.sku_id );
      item.cart_num = itemCart && itemCart.length ? itemCart[0].num : 0;
      return item;
    });
    return useNewData;
  },
  // 监听方法,监听团购购物车
  watch(method){
    let obj = this.globalData;
    Object.defineProperty(obj, 'cart', {
      configurable: true,
      enumerable: true,
      set: function (value) {
        this.cart = value;
        method(value);
      },
      get: function() {
        return this.cart
      }
    })
  }
});